package com.swotxu.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.swotxu.common.constant.MallUrlConstant;
import com.swotxu.common.to.es.SkuESModel;
import com.swotxu.common.utils.R;
import com.swotxu.mall.search.config.MallElasticSearchConfig;
import com.swotxu.mall.search.constant.ESConstant;
import com.swotxu.mall.search.feign.ProductFeignService;
import com.swotxu.mall.search.service.MallSearchService;
import com.swotxu.mall.search.vo.AttrResponseVo;
import com.swotxu.mall.search.vo.BrandVo;
import com.swotxu.mall.search.vo.SearchParam;
import com.swotxu.mall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Date: 2021/1/27 22:08
 * @Author: swotXu
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        // 检索结果
        SearchResult result = null;
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse searchResponse = client.search(searchRequest, MallElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据为需要的格式
            result = buildSearchResult(param, searchResponse);
        } catch (IOException e) {
            log.warn("检索异常!", e);
        }
        return result;
    }

    /**
     * 构建检索请求
     * 模糊匹配，过滤（按照属性、分类、品牌、价格区间、库存），排序，分页，高亮，聚合分析
     * @param searchParam   请求检索项
     * @return  es检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // ------- 1、模糊匹配，过滤（按照属性、分类、品牌、价格区间、库存） -------
        // 构建 bool 查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、bool - must
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        // 1.2 bool - fliter
        // 1.2.1 term - catalogId   三级分类id
        if (searchParam.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // 1.2.2 terms - [brandId, brandId] 品牌id
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 1.2.3 nested - attrs 属性查询
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attr=1_其他:安卓
                String[] s = attr.split("_");
                String attrId = s[0];   // 属性id
                String[] attrValues = s[1].split(":"); // 属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个属性都必须生成一个 nestedQuery 嵌入式查询
                boolQuery.filter(QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None));
            }
        }
        // 1.2.4 term - hasStock 库存
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock()==1));
        }
        // 1.2.5 range - skuPrice 价格区间  0_500/_500/500_
        if (StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] range = searchParam.getSkuPrice().split("_");
            if (searchParam.getSkuPrice().endsWith("_")) {
                rangeQuery.gte(range[0]);
            } else if (searchParam.getSkuPrice().startsWith("_")) {
                rangeQuery.lte(range[1]);
            } else if (range.length == 2){
                rangeQuery.gte(range[0]).lte(range[1]);
            }
            boolQuery.filter(rangeQuery);
        }
        // 最后封装所有的查询条件 boolQuery
        builder.query(boolQuery);

        // ------- 2、排序，分页，高亮 -------
        // 2.1、构建 sort 排序   saleCount_asc 销量排序、 skuPrice_asc/desc 价格排序、 hotScore_asc/desc 热度评分（综合排序）
        if (StringUtils.isNotBlank(searchParam.getSort())) {
            String[] sort = searchParam.getSort().split("_");
            builder.sort(sort[0], SortOrder.fromString(sort[1]));
        }
        // 2.2、构建 page 分页  from = (pageNum -1) * PAGE_SIZE
        builder.from((searchParam.getPageNum() -1) * ESConstant.PRODUCT_PAGE_SIZE);
        builder.size(ESConstant.PRODUCT_PAGE_SIZE);
        // 2.3、构建 highlight 高亮
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder()
                    .field("skuTitle").preTags("<b style='color:red'>").postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        // ------- 3、聚合分析 -------
        // 3.1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 3.1.1、子聚合 - 品牌名
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        brandAgg.subAggregation(brandNameAgg);
        // 3.1.1、子聚合 - 品牌图片
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brandAgg.subAggregation(brandImgAgg);

        builder.aggregation(brandAgg);

        // 3.2、分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        // 3.2.1、子聚合 - 分类名
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1);
        catalogAgg.subAggregation(catalogNameAgg);

        builder.aggregation(catalogAgg);

        // 3.3、属性聚合
        NestedAggregationBuilder attrNestedAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 属性id聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        // 3.3.1、子聚合 - 属性名
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 3.3.2、子聚合 - 属性值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrNestedAgg.subAggregation(attrIdAgg);

        builder.aggregation(attrNestedAgg);

        System.out.println("====================");
        System.out.println(builder.toString());
        return new SearchRequest(new String[]{ESConstant.PRODUCT_INDEX}, builder);
    }

    /**
     * 构建响应结果
     *
     * @param searchParam
     * @param searchResponse  es响应数据
     * @return  自定义响应结果
     */
    private SearchResult buildSearchResult(SearchParam searchParam, SearchResponse searchResponse) {
        SearchResult result = new SearchResult();
        // 1、封装查询到的商品
        List<SkuESModel> skuESModelList = Optional.ofNullable(searchResponse.getHits().getHits())
                .map(hits -> Arrays.stream(hits)
                        .map(hit -> {
                            SkuESModel skuESModel = JSON.parseObject(hit.getSourceAsString(), SkuESModel.class);
                            if (StringUtils.isNotBlank(searchParam.getKeyword())) {
                                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                                skuESModel.setSkuTitle(skuTitle.getFragments()[0].string());
                            }
                            return skuESModel;
                        })
                        .collect(Collectors.toList()))
                .orElse(Collections.emptyList());
        result.setProducts(skuESModelList);

        // 2、封装所有商品涉及到的属性信息
        ParsedNested attrNestedAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrNestedAgg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = attrIdAgg.getBuckets().stream().map(bucket -> {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 得到属性ID
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            // 从子聚合中得到属性名
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            // 从子聚合中得到属性值 - 多个
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> values = attrValueAgg.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(values);

            return attrVo;
        }).collect(Collectors.toList());
        result.setAttrs(attrVos);

        // 3、封装所有商品涉及到的品牌信息
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = brandAgg.getBuckets().stream().map(bucket -> {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 得到品牌ID
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            // 从子聚合中得到品牌名
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            brandVo.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());
            // 从子聚合中得到品牌图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());

            return brandVo;
        }).collect(Collectors.toList());
        result.setBrands(brandVos);

        // 4、封装所有商品涉及到的分类信息
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = catalogAgg.getBuckets().stream().map(bucket -> {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 得到分类ID
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 从子聚合中得到分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            catalogVo.setCatalogName(catalogNameAgg.getBuckets().get(0).getKeyAsString());

            return catalogVo;
        }).collect(Collectors.toList());
        result.setCatalogs(catalogVos);

        // 5、封装分页信息 totalPage = total/PRODUCT_PAGE_SIZE || total/PRODUCT_PAGE_SIZE +1
        long total = searchResponse.getHits().getTotalHits().value;
        int totalPage = (int)total%ESConstant.PRODUCT_PAGE_SIZE == 0?
                (int)total/ESConstant.PRODUCT_PAGE_SIZE : (int)total/ESConstant.PRODUCT_PAGE_SIZE +1;
        result.setTotal(total);
        result.setTotalPages(totalPage);
        result.setPageNum(searchParam.getPageNum());

        // 6、构建面包屑导航功能
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            List<SearchResult.NavVo> navVos = searchParam.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                // attrs=1_其他:安卓
                String[] attrNameAndValues = attr.split("_");
                navVo.setNavValue(attrNameAndValues[1]);
                // 远程调用获取属性名
                R attrInfoResult = productFeignService.attrInfo(Long.parseLong(attrNameAndValues[0]));
                if (attrInfoResult.isOk()) {
                    AttrResponseVo attrVo = attrInfoResult.getValue("attr",new TypeReference<AttrResponseVo>() {});
                    navVo.setNavName(attrVo.getAttrName());
                } else {
                    navVo.setNavName(attrNameAndValues[0]);
                }
                // 设置请求参数携带的品牌ID
                result.getAttrIds().add(Long.parseLong(attrNameAndValues[0]));
                // 取消面包屑后，我们要跳转到那个地方，将请求地址的url里面的当前置空
                // 拿到所有的查询条件，去掉当前。 attrs=1_LIO-AN00m
                String newQueryString = replaceQueryString(searchParam.get_queryString(), "attrs", attr);
                navVo.setLink(MallUrlConstant.SEARCH_URL_LIST + newQueryString);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        // 7、如果请求中携带品牌参数，则加入面包屑导航
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            R brandsRes = productFeignService.brandInfos(searchParam.getBrandId());
            if (brandsRes.isOk()) {
                String queryString = searchParam.get_queryString();
                StringBuilder sb = new StringBuilder();
                List<BrandVo> brandInfoVos = brandsRes.getData(new TypeReference<List<BrandVo>>() {});
                for (BrandVo brandInfoVo : brandInfoVos) {
                    sb.append(brandInfoVo.getName()).append(";");
                    queryString = replaceQueryString(queryString, "brandId", String.valueOf(brandInfoVo.getBrandId()));
                }
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavName("品牌");
                navVo.setNavValue(sb.toString());
                navVo.setLink(MallUrlConstant.SEARCH_URL_LIST + queryString);
                result.getNavs().add(navVo);
            }
        }
        // TODO 8、分类同上（不需要导航取消，可不拼接url）
        return result;
    }

    private String replaceQueryString(String url, String key, String val) {
        String encode = null;
        try {
            encode = URLEncoder.encode(val, "UTF-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url.replaceAll("&*?"+key+"=" + encode, StringUtils.EMPTY);
    }
}
